package com.baidu.leetcode.yangge.utils;

import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.function.Consumer;

/**
 * JUS百万下发批处理工具类
 */
public class TaskBatchSendUtils {

    /*
      下发邮件 优惠卷 短信 等通用方法
     */
    public static <T> void send(List<T> taskList, Executor threadPool, Consumer<? super T> consumer) throws InterruptedException {
        if (CollectionUtils.isEmpty(taskList)) {
            return;
        }
        if (Objects.isNull(consumer)) {
            return;
        }
        CountDownLatch countDownLatch = new CountDownLatch(taskList.size());
        for (T data: taskList) {
            threadPool.execute(()->{
                try{
                    consumer.accept(data);
                }finally {
                    countDownLatch.countDown();
                }
            });
        }
        countDownLatch.await();
    }

    public static void disposeTask(String task) {
        System.out.println("业务处理1");
    }

    public static void disposeTaskV2(String task) {
        System.out.println("业务处理2");
    }

    public static void disposeTaskV3(String task) {
        System.out.println("业务处理3");
    }



    public static void main(String[] args) throws InterruptedException {

        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        List<String> coupons = new ArrayList<>();
        List<String> orders = new ArrayList<>();
        List<String> datas = new ArrayList<>();
        //调用工具类批处理任务
        TaskBatchSendUtils.send(coupons,threadPoolTaskExecutor,TaskBatchSendUtils::disposeTask);

        TaskBatchSendUtils.send(orders,threadPoolTaskExecutor,TaskBatchSendUtils::disposeTaskV2);

        TaskBatchSendUtils.send(datas,threadPoolTaskExecutor,TaskBatchSendUtils::disposeTaskV3);
    }









}
